<template>
  <div class="table1_container">
    <div class="table1_dataShower" style="padding-bottom: 50px; padding-top: 50px; box-sizing: border-box">
      <button class="report-top-button" @click="back">返回上级页面</button>
      <button class="report-top-button" @click="print">打印报表</button>
      <div style="text-align: center; margin: 10px 0;">
        <div style="display: inline-flex; gap: 20px;">
          <!-- 未完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffffff; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>未完成</span>
          </div>

          <!-- 已完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #e6f7e6; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>已完成</span>
          </div>

          <!-- 不合格重采 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffebeb; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>不合格重采</span>
          </div>
        </div>
      </div>
      <div class="fenbu-normal-table">
        <h1>{{ reportData.fenbuName }}工程质量验收记录</h1>
        <span class="table1_reportId" style="text-align: right; display: block;margin-right:23%; margin-bottom: 3px;"
        >{{ '编号：' }}</span>
        <table class="fenbu-table1_top_table">
        <tr>
          <td colspan="4" style="font-weight: 700;">单位（子单位）工程名称</td>
          <td colspan="13">{{ reportData.subprojectName }}</td>
          <td colspan="4" style="font-weight: 700;">子分部工程数量</td>
          <td colspan="5">{{ reportData.subfenbuAmount }}</td>
          <td colspan="4" style="font-weight: 700;">分项工程数量</td>
          <td colspan="5">{{ reportData.fenxiangAmount }}</td>
        </tr>
        <tr>
          <td colspan="4" style="font-weight: 700;">施工单位</td>
          <td colspan="13">{{ reportData.shigongCompanyName }}</td>
          <td colspan="4" style="font-weight: 700;">项目负责人</td>
          <td colspan="5">{{ reportData.shigongDirector }}</td>
          <td colspan="4" style="font-weight: 700;">技术（质量）负责人</td>
          <td colspan="5">{{ reportData.technicalDirector }}</td>
        </tr>
        <tr>
          <td colspan="4" style="font-weight: 700;">分包单位</td>
          <td colspan="13">{{ reportData.fenbaoData.fenbaoCompany }}</td>
          <td colspan="4" style="font-weight: 700;">分包单位<br>负责人</td>
          <td colspan="5">{{ reportData.fenbaoData.fenbaoDirector }}</td>
          <td colspan="4" style="font-weight: 700;">分包单位<br>技术负责人</td>
          <td colspan="5">{{ reportData.fenbaoData.fenbaoTechnical }}</td>
        </tr>
        <tr>
          <td colspan="2" style="font-weight: 700;">序号</td>
          <td colspan="6" style="font-weight: 700;">子分部工程名称</td>
          <td colspan="6" style="font-weight: 700;">分项工程名称</td>
          <td colspan="3" style="font-weight: 700;">检验批数量</td>
          <td colspan="9" style="font-weight: 700;">施工单位检查结果</td>
          <td colspan="9" style="font-weight: 700;">监理单位验收结论</td>
        </tr>
        <tr v-for="(item, index) in reportData.items" :key="index">
          <td colspan="2">{{ item.fenxiangName ? index + 1 : '' }}</td>
          <td colspan="6">{{ item.subfenbuName }}</td>
          <td colspan="6">{{ item.fenxiangName }}</td>
          <td colspan="3">{{ item.taskAmount }}</td>
          <td colspan="9" class="checkResult">{{ item.fenxiangName ? item.checkResult : '' }}</td>
          <td colspan="9">{{ item.fenxiangName ? item.checkConclusion : '' }}</td>
        </tr>
        <tr>
          <td colspan="17" style="font-weight: 700;">质量控制资料</td>
          <td colspan="9">质量证明资料齐全</td>
          <td colspan="9"></td>
        </tr>
        <tr>
          <td colspan="17" style="font-weight: 700;">安全和功能检验结果</td>
          <td colspan="9">合格</td>
          <td colspan="9"></td>
        </tr>
        <tr>
          <td colspan="17" style="font-weight: 700;">观感质量检验结果</td>
          <td colspan="9">好</td>
          <td colspan="9"></td>
        </tr>
        <tr class="table1_conclusion">
          <td style="height: 250px; writing-mode: vertical-rl;text-orientation: upright; font-weight: 700" colspan="2">
            综合验收结论
          </td>
          <td class="fenbu_enter" style="height: 250px" colspan="33">合格</td>
        </tr>
        <tr>
          <td class="fenbuName" colspan="8">施工单位<br>项目负责人：</td>
          <td class="fenbuName" colspan="9">勘察单位<br>项目负责人：</td>
          <td class="fenbuName" colspan="9">设计单位<br>项目负责人：</td>
          <td class="fenbuName" colspan="9">监理单位<br>总监理工程师：</td>
        </tr>
        <tr>
          <td class="fenbutrueName" style="height: 150px;border-top-width: 0" colspan="8"></td>
          <td class="fenbutrueName" style="height: 150px;border-top-width: 0" colspan="9"></td>
          <td class="fenbutrueName" style="height: 150px;border-top-width: 0" colspan="9"></td>
          <td class="fenbutrueName" style="height: 150px;border-top-width: 0" colspan="9"></td>
        </tr>
        <tr>
          <td class="fenbudate" colspan="8">年 月 日</td>
          <td class="fenbudate" colspan="9">年 月 日</td>
          <td class="fenbudate" colspan="9">年 月 日</td>
          <td class="fenbudate" colspan="9">年 月 日</td>
        </tr>
      </table>
      </div>
      <!-- 打印显示：分页格式（通过方法动态生成） -->
      <div class="fenbu-pages" ref="fenbuPagesContainer" style="display: none;"></div>
    </div>
  </div>
</template>

<script>
import { searchFenbuCheckPreview } from '@/api/statementManage/yanShou/statementManage'

const PAGE_ROW_LIMIT = 8
/*
 *    这个报表真麻烦！！！
 *
 */

export default {
  data() {
    return {
      localStorageId: '',
      reportData: {
        items: [],
        fenbaoData: {}
      },
      previewData: {},
      receivedData: {},
      pageRowLimit: PAGE_ROW_LIMIT
    }
  },
  computed: {
    preparedItems() {
      const items = (this.reportData.items || []).map(item => ({ ...item }))
      let serial = 1
      items.forEach(item => {
        if (item.fenxiangName) {
          item.__serial = serial++
        }
      })
      return items
    },
    pagedItems() {
      const pages = []
      let current = []
      let countedRows = 0
      const source = this.preparedItems

      source.forEach(item => {
        const isCountable = this.isCountableRow(item)
        if (isCountable && countedRows === this.pageRowLimit) {
          pages.push(current)
          current = []
          countedRows = 0
        }
        current.push(item)
        if (isCountable) {
          countedRows++
        }
      })

      if (current.length || pages.length === 0) {
        pages.push(current)
      }

      return pages
    }
  },
  async mounted() { // 钩子函数
    this.receivedData = JSON.parse(sessionStorage.getItem('tempObj1'))
    console.log(this.receivedData)

    const { result } = await searchFenbuCheckPreview(this.receivedData.subprojectId, this.receivedData.fenbuId)

    this.reportData = {
      ...result,
      items: result.items || [],
      fenbaoData: result.fenbaoData || {}
    }

    console.log(result)
    console.log(JSON.stringify(this.reportData))

  },
  beforeDestroy() { // 离开页面要做的事
    // 那就是清除localstorage！！！
    if (this.localStorageId) {
      localStorage.removeItem(this.localStorageId)
    }
    document.querySelector('body').setAttribute('style', 'background-color: white;') // 还原，因为这是个全局样式
  },
  beforeCreate() {
    document.querySelector('body').setAttribute('style', 'background-color:#f5f5f5;') // 设置对比色
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    print() {
      // 在打印前生成分页HTML
      this.generatePagedHTML()
      window.print()
    },
    generatePagedHTML() {
      // 生成分页HTML的方法
      const container = this.$refs.fenbuPagesContainer
      if (!container) return

      // 清空容器
      container.innerHTML = ''

      const pages = this.pagedItems
      const data = this.reportData

      pages.forEach((pageItems, pageIndex) => {
        const pageDiv = document.createElement('div')
        pageDiv.className = 'fenbu-page'

        // 生成页面HTML
        let html = `
          <h1>${data.fenbuName}工程质量验收记录</h1>
          <span class="table1_reportId" style="text-align: right; display: block;margin-right:23%; margin-bottom: 3px;">编号：</span>
          <table class="fenbu-table1_top_table">
            <thead>
              <tr>
                <td colspan="4" style="font-weight: 700;">单位（子单位）工程名称</td>
                <td colspan="13">${data.subprojectName || ''}</td>
                <td colspan="4" style="font-weight: 700;">子分部工程数量</td>
                <td colspan="5">${data.subfenbuAmount || ''}</td>
                <td colspan="4" style="font-weight: 700;">分项工程数量</td>
                <td colspan="5">${data.fenxiangAmount || ''}</td>
              </tr>
              <tr>
                <td colspan="4" style="font-weight: 700;">施工单位</td>
                <td colspan="13">${data.shigongCompanyName || ''}</td>
                <td colspan="4" style="font-weight: 700;">项目负责人</td>
                <td colspan="5">${data.shigongDirector || ''}</td>
                <td colspan="4" style="font-weight: 700;">技术（质量）负责人</td>
                <td colspan="5">${data.technicalDirector || ''}</td>
              </tr>
              <tr>
                <td colspan="4" style="font-weight: 700;">分包单位</td>
                <td colspan="13">${(data.fenbaoData && data.fenbaoData.fenbaoCompany) || ''}</td>
                <td colspan="4" style="font-weight: 700;">分包单位<br>负责人</td>
                <td colspan="5">${(data.fenbaoData && data.fenbaoData.fenbaoDirector) || ''}</td>
                <td colspan="4" style="font-weight: 700;">分包单位<br>技术负责人</td>
                <td colspan="5">${(data.fenbaoData && data.fenbaoData.fenbaoTechnical) || ''}</td>
              </tr>
              <tr>
                <td colspan="2" style="font-weight: 700;">序号</td>
                <td colspan="6" style="font-weight: 700;">子分部工程名称</td>
                <td colspan="6" style="font-weight: 700;">分项工程名称</td>
                <td colspan="3" style="font-weight: 700;">检验批数量</td>
                <td colspan="9" style="font-weight: 700;">施工单位检查结果</td>
                <td colspan="9" style="font-weight: 700;">监理单位验收结论</td>
              </tr>
            </thead>
            <tbody>
        `

        // 生成数据行
        pageItems.forEach(item => {
          const serial = item.__serial || ''
          html += `
            <tr class="fenbu-body-row">
              <td colspan="2">${serial}</td>
              <td colspan="6">${item.subfenbuName || ''}</td>
              <td colspan="6">${item.fenxiangName || ''}</td>
              <td colspan="3">${item.taskAmount || ''}</td>
              <td colspan="9" class="checkResult">${item.fenxiangName ? (item.checkResult || '') : ''}</td>
              <td colspan="9">${item.fenxiangName ? (item.checkConclusion || '') : ''}</td>
            </tr>
          `
        })

        // 添加占位行
        const counted = pageItems.filter(item => this.isCountableRow(item)).length
        const fillerCount = Math.max(this.pageRowLimit - counted, 0)
        for (let i = 0; i < fillerCount; i++) {
          html += `
            <tr class="fenbu-body-row is-placeholder">
              <td colspan="2"></td>
              <td colspan="6"></td>
              <td colspan="6"></td>
              <td colspan="3"></td>
              <td colspan="9" class="checkResult"></td>
              <td colspan="9"></td>
            </tr>
          `
        }

        // 生成验收区域
        html += `
            </tbody>
            <tfoot>
              <tr>
                <td colspan="17" style="font-weight: 700;">质量控制资料</td>
                <td colspan="9">质量证明资料齐全</td>
                <td colspan="9"></td>
              </tr>
              <tr>
                <td colspan="17" style="font-weight: 700;">安全和功能检验结果</td>
                <td colspan="9">合格</td>
                <td colspan="9"></td>
              </tr>
              <tr>
                <td colspan="17" style="font-weight: 700;">观感质量检验结果</td>
                <td colspan="9">好</td>
                <td colspan="9"></td>
              </tr>
              <tr class="table1_conclusion">
                <td style="height: 250px; writing-mode: vertical-rl;text-orientation: upright; font-weight: 700" colspan="2">综合验收结论</td>
                <td class="fenbu_enter" style="height: 250px" colspan="33">合格</td>
              </tr>
              <tr>
                <td class="fenbuName" colspan="8">施工单位<br>项目负责人：</td>
                <td class="fenbuName" colspan="9">勘察单位<br>项目负责人：</td>
                <td class="fenbuName" colspan="9">设计单位<br>项目负责人：</td>
                <td class="fenbuName" colspan="9">监理单位<br>总监理工程师：</td>
              </tr>
              <tr>
                <td class="fenbutrueName" style="height: 150px;border-top-width: 0" colspan="8"></td>
                <td class="fenbutrueName" style="height: 150px;border-top-width: 0" colspan="9"></td>
                <td class="fenbutrueName" style="height: 150px;border-top-width: 0" colspan="9"></td>
                <td class="fenbutrueName" style="height: 150px;border-top-width: 0" colspan="9"></td>
              </tr>
              <tr>
                <td class="fenbudate" colspan="8">年 月 日</td>
                <td class="fenbudate" colspan="9">年 月 日</td>
                <td class="fenbudate" colspan="9">年 月 日</td>
                <td class="fenbudate" colspan="9">年 月 日</td>
              </tr>
            </tfoot>
          </table>
        `

        pageDiv.innerHTML = html
        container.appendChild(pageDiv)
      })
    },
    isCountableRow(item) {
      return !!(item && item.fenxiangName && !item.__placeholder)
    }
  }
}
</script>

<style>
@import '../../../../assets/css/yanshou/fenbuCheck.css';

/*
先来设置每个任务项对应的背景颜色吧！
 */
.row-unfinished {
  background-color: #ffffff; /* 未完成 - 白色或默认色 */
}

.row-finished {
  background-color: #e6f7e6; /* 已完成 - 浅绿色 */
}

.row-failed {
  background-color: #ffebeb; /* 不合格重采 - 浅红色 */
}

.table1_container {
  width: 70%;
  background: white;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding-bottom: 20px;
}

.table1_dataShower {
  width: 80%;
  background: white;
  margin: 0 auto;
  border: 2px black solid;
}

/* 正常显示：原表格 */
.fenbu-normal-table {
  display: block;
}

/* 打印显示：分页格式 - 正常时隐藏 */
.fenbu-pages {
  display: none;
  width: 100%;
}

.fenbu-page {
  margin-bottom: 30px;
  page-break-after: none;
}

.fenbu-page:last-child {
  margin-bottom: 0;
}

.fenbu-body-row td {
  height: 48px;
  min-height: 48px;
}

/* 非打印模式下隐藏占位行 */
.fenbu-body-row.is-placeholder {
  display: none;
}

/*这是返回按钮的样式*/
.report-top-button {
  display: block;
  margin: 0 auto;
  margin-bottom: 20px;
  padding: 12px 28px;
  font-size: 16px;
  font-weight: 600;
  font-family: 'Arial', sans-serif;
  color: #ffffff;
  background: linear-gradient(90deg, #1e3a8a, #3b82f6); /* 建筑行业蓝色调，稳重且有活力 */
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.report-top-button:hover {
  background: linear-gradient(90deg, #1e3a8a, #2563eb);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.report-top-button:active {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  transform: translateY(0);
}

/*表格样式*/
.fenbu-table1_top_table {
  width: 90%;
  margin: 0 auto;
  border-collapse: collapse;
  border: 1px solid black;
  table-layout: fixed;
}

/*表格的样式*/
.fenbu-table1_top_table tr td {
  height: 70px;
  min-height: 70px;
  border: 1px solid black;
  word-wrap: break-word; /* 允许长单词换行 */
  overflow-wrap: break-word; /* 更现代的换行属性 */
}

#table1_top_table_last_col {
  width: 20%;
  min-height: 50px;
}

th {
  box-sizing: border-box !important;
}

.fenbu-table1_top_table .fenbuName {
  text-align: left;
  border-bottom-width: 0;
  font-weight: 700;
  padding-left: 5px;
}

.fenbu-table1_top_table .fenbutrueName {
  height: 150px;
  border-top-width: 0;
  border-bottom-width: 0;
}

.fenbu-table1_top_table .fenbudate {
  text-align: right;
  border-top-width: 0;
  letter-spacing: 1em;
}

@media print {
  @page {
    size: A4 portrait;
  }

  .table1_dataShower {
    padding: 0 !important;
  }

  /* 打印时隐藏原表格 */
  .fenbu-normal-table {
    display: none !important;
  }

  /* 打印时显示分页视图 */
  .fenbu-pages {
    display: block !important;
    width: 100% !important;
  }

  .fenbu-page {
    display: block !important;
    margin-bottom: 0;
    /* 打印模式下启用分页 */
    page-break-after: always;
    width: 100% !important;
  }

  .fenbu-page:last-child {
    page-break-after: auto;
  }

  /* 打印模式下显示占位行 */
  .fenbu-body-row.is-placeholder {
    display: table-row !important;
  }

  .fenbu-body-row.is-placeholder td {
    color: transparent;
  }

  .fenbu-table1_top_table {
    width: 100% !important;
    max-width: 100% !important;
  }
}
</style>
